import React, { FC, memo, useEffect, useState, useRef } from 'react'
import '@/scss/Home.scss'
import websocketClient from '@/api/WebSocketClient'
import { useSearchParams } from 'react-router-dom'
import * as ModelProto from '@/proto/model/ModelProto'
import { Command, MediaType } from '@/const/Constants'
import { Toast } from 'antd-mobile'
import { random32 } from '@/utils/RandomUtil'
interface NavigationObj {
  icon: string
  title: string
}

interface MessageObj {
  from: string
  target: string
  identityType: number //发送人的身份 0客服1用户信息
  messageType: number //消息类型 1文本2图片
  content: string //消息体
}



const Home: FC = () => {
  const [searchParams] = useSearchParams()
  const chatBodyRef = useRef<HTMLDivElement>(null)
  const [textMessage, setTextMessage] = useState<string>('')

  const [customer, setCustomer] = useState(null);

  const [messageList, setMessageList] = useState<MessageObj[]>([
    {
      from: '1',
      target: '2',
      identityType: 0,
      messageType: 1,
      content: '你好! 很高兴为你服务 速度速'
    },
    {
      from: '2',
      target: '1',
      identityType: 1,
      messageType: 1,
      content: '能提现吗'
    }
  ])


  useEffect(() => {
    console.log('首页渲染')

    //从Url获取认证参数
    let request = createAuthRequest()

    //连接websocket
    websocketClient.connect(request)

    // 清理函数（可选）: 当组件卸载时关闭WebSocket连接等清理工作。
    return () => {
      websocketClient.disconnect() // 关闭WebSocket连接
    }
  }, [])

  useEffect(() => {
    chatBodyRef.current?.scrollTo({
      top: chatBodyRef.current.scrollHeight,
      behavior: 'smooth'
    })
  }, [messageList])

  //定义导航列表
  const navigationList: NavigationObj[] = [
    {
      icon: new URL('@/assets/img/会员导购.png', import.meta.url).href,
      title: '会员导购'
    },
    {
      icon: new URL('@/assets/img/续费管理.png', import.meta.url).href,
      title: '续费管理'
    },
    {
      icon: new URL('@/assets/img/激活码.png', import.meta.url).href,
      title: '激活码'
    },
    {
      icon: new URL('@/assets/img/会员转移.png', import.meta.url).href,
      title: '会员转移'
    }
  ]

  const issueList: String[] = [
    '续费管理',
    '下载文件位置',
    '账号异常',
    '会员未生效'
  ]

  //发送消息后续处理...
  const sendTextAfter = () => {
    //1.构建消息体
    let message = {
      from: '1',
      target: '2',
      identityType: 1,
      messageType: 1,
      content: textMessage
    }

    setMessageList((preList) => [...preList, message])
  }

  //发送消息
  const handleTexSend = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key == 'Enter') {
      if (textMessage == '' || !textMessage) {
        return
      }
      //回车事件
      //TODO  发送消息到服务器
      if (!websocketClient.isAuthorized) {
        Toast.show({
          icon: 'fail',
          content: '请先认证'
        })
        return;
      }

      //组装消息
      let request = ModelProto.Request.create()
      let header = initHeader(Command.MESSAGE)
      request.header = header
      let chatPack = ModelProto.ChatPack.create();
      chatPack.content = textMessage
      chatPack.mediaType = MediaType.TEXT
      request.chat = chatPack
      websocketClient.sendMessage(request)

      //发送消息成功追加到消息底部
      sendTextAfter()

      //将数据清空
      setTextMessage('')
    }
  }

  const createAuthRequest = (): ModelProto.Request => {
    //获取请求参数
    let projectCode = searchParams.get("projectCode")
    let cipherText = searchParams.get('cipherText')
    let secretKey = searchParams.get('secretKey')

    let request = ModelProto.Request.create();
    let header = ModelProto.Header.create();
    header.command = Command.AUTH;
    header.projectCode = projectCode ? projectCode : ''
    request.header = header;
    let authPack = ModelProto.AuthPack.create()
    authPack.cipherText = cipherText ? cipherText : ''
    authPack.secretKey = secretKey ? secretKey : ''
    request.auth = authPack;
    return request
  }

  const initHeader = (command: Command): ModelProto.Header => {
    const header = ModelProto.Header.create();
    header.command = command;
    let projectCode = searchParams.get("projectCode")
    header.projectCode = projectCode ? projectCode : ''
    header.version = import.meta.env.VITE_PROJECT_VERSION
    header.reqId = random32()
    return header;
  }

  return (
    <div className="app-container">
      <div className="body">
        <div className="title">
          <img
            alt="回退"
            src={new URL('@/assets/img/back.png', import.meta.url).href}
            height={15}
          />
          <>用户客服</>
        </div>

        <div className="chat-content">
          <div className="chat-tips-text">
            <div className="hi">
              <p>Hi 有什么可以帮你 ? </p>
              <p>小彩为你服务~ </p>
            </div>
            <div className="img">
              <img
                src={
                  new URL('@/assets/img/ai-chat-bc.png', import.meta.url).href
                }
                height={111}
              />
            </div>
          </div>
          <div className="c-navigation">
            {navigationList.map((item: NavigationObj, index: number) => {
              return (
                <div key={index} className="nav-item">
                  <img src={item.icon} height={28.83}></img>
                  <p>{item.title}</p>
                </div>
              )
            })}
          </div>

          <div className="message-body" ref={chatBodyRef}>
            {/* 猜你想问 */}
            <div className="guess-issue">
              <div className="ai-avatar">
                <img
                  src={
                    new URL('@/assets/img/ai-avatar.png', import.meta.url).href
                  }
                  height={40}
                  alt="客服头像"
                />
              </div>
              <div className="issue-content">
                <div className="issue-title issue-item">
                  <>猜你想问?</>
                  <div className="title-refrensh">
                    <img
                      src={
                        new URL('@/assets/img/刷新.png', import.meta.url).href
                      }
                      height={13}
                      alt="机器人"
                    />
                    <span>换一换</span>
                  </div>
                </div>

                {issueList.map((issueItem: String, index: number) => {
                  return (
                    <div className="issue-item" key={index}>
                      {issueItem}
                    </div>
                  )
                })}
              </div>
            </div>

            <div className="message-list">
              {messageList.length > 0 &&
                messageList.map((item, index) =>
                  item.identityType == 0 ? (
                    <div className="message-item customer-message" key={index}>
                      <div className="ai-avatar avatar">
                        <img
                          src={
                            new URL(
                              '@/assets/img/ai-avatar.png',
                              import.meta.url
                            ).href
                          }
                          height={40}
                          alt="客服头像"
                        />
                      </div>
                      <div className="message-content customer-content">
                        {item.content}
                      </div>
                    </div>
                  ) : (
                    <div className="message-item user-message" key={index}>
                      <div className="message-content user-content">
                        {item.content}
                      </div>
                      <div className="user-avatar avatar">
                        <img
                          src={
                            new URL(
                              '@/assets/img/u-avatar.png',
                              import.meta.url
                            ).href
                          }
                          height={40}
                          alt="用户头像"
                        />
                      </div>
                    </div>
                  )
                )

              }
            </div>
          </div>
          <div className="message-list">
            {
              /**
               * 消息列表
               */
              messageList.length > 0 &&
              messageList.map((item, index) => (
                <div key={index} className="message-list-item">
                  <div className="avatar"></div>
                  <div className="message"></div>
                </div>
              ))
            }
          </div>
        </div>
      </div>
      <div className="bottom-send">
        {
          customer ? (<div className='send-msg-box'>
            <div className="text-input" onKeyDown={handleTexSend}>
              <input
                type="text"
                value={textMessage}
                onChange={(e) => setTextMessage(e.target.value)}
              />
              <img
                alt="表情"
                src={new URL('@/assets/img/表情.png', import.meta.url).href}
                height={31}
              />
            </div>
            <div className="img-upload">
              <img
                src={new URL('@/assets/img/add.png', import.meta.url).href}
                height={31}
                alt="发送图片"
              />
            </div>

          </div>) : (
            <div className="dispatch-btn">
              <img
                src={
                  new URL('@/assets/img/ai-chat-bc.png', import.meta.url).href
                }
                height={20}
              />
              <div>人工客服</div>
            </div>

          )

        }

      </div>
    </div>
  )
}

export default memo(Home)
